package com.kennedy.atoupdate.service;

import com.github.pagehelper.PageHelper;
import com.kennedy.atoupdate.beans.VersionInfo;
import com.kennedy.atoupdate.beans.user.SysRole;
import com.kennedy.atoupdate.beans.user.SysUser;
import com.kennedy.atoupdate.mapper.SysUserMapper;
import com.kennedy.atoupdate.mapper.VersionInfoMapper;
import com.kennedy.atoupdate.utils.DateUtil;
import com.kennedy.atoupdate.utils.FileUploadUtil;
import com.kennedy.atoupdate.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by tao.zeng on 2017/8/2.
 */
@Service
public class VersionInfoService {
    @Autowired
    private VersionInfoMapper versionInfoMapper;
    @Value("${staticPath}")
    private String staticPath;
    @Value("${linuxOTASHPath}")
    private String linuxOTASHPath;


    public List<VersionInfo> getListByPage(VersionInfo versionInfo) {
        if (versionInfo.getOffset() != null && versionInfo.getLimit() != null) {
            PageHelper.offsetPage(versionInfo.getOffset(), versionInfo.getLimit());
        }
        Example example = new Example(VersionInfo.class);
        Example.Criteria criteria = example.createCriteria();
        if (versionInfo.getType() != null) {
            criteria.andEqualTo("type", versionInfo.getType());
        }
        List<VersionInfo> versionInfos = versionInfoMapper.selectByExample(example);
        return versionInfos;
    }

    @Transactional
    public void insert(VersionInfo versionInfo, MultipartFile file) {
        versionInfo.setCreateTime(DateUtil.getCurrentTime());
        versionInfoMapper.insert(versionInfo);
        FileUploadUtil.uploadFile(file, staticPath + "/" + versionInfo.getType() + "/pkg" + "/" + versionInfo.getVersion());
        // 差分
        VersionInfo query = new VersionInfo();
        query.setOffset(null);
        query.setLimit(null);
        query.setType(versionInfo.getType());
        List<VersionInfo> versionInfos = getListByPage(query);
        if (versionInfos.size() > 0) {
            for (VersionInfo version : versionInfos) {
                if (version.getVersion().equals(versionInfo.getVersion())) {
                    continue;
                }
                String cmd = linuxOTASHPath + " " + versionInfo.getType() + "/pkg/" + version.getVersion() + " " + versionInfo.getType() + "/pkg/" + versionInfo.getVersion() + " " + staticPath + "/" + versionInfo.getType() + "/updatepkg/" + version.getVersion() + "/update.zip";
                String shdir = linuxOTASHPath.substring(0, linuxOTASHPath.lastIndexOf("/"));
                Process process;
                try {
                    process = Runtime.getRuntime().exec(cmd, null, new File(shdir));
                    System.out.println("执行shell命令: " + cmd + "\r\n命令返回：" + process.waitFor());
                    File f = new File(staticPath + "/" + versionInfo.getType() + "/updatepkg/" + version.getVersion() + "/update.zip");
                    version.setSize((int) (f.length() / 1024 / 1024) + 1);
                    version.setUpdateTime(DateUtil.getCurrentTime());
                    version.setMd5(MD5Util.fileMD5(f.getPath()));
                    versionInfoMapper.updateByPrimaryKey(version);
                } catch (Exception e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    e.printStackTrace();
                }
            }
        }
    }

    public VersionInfo getLastVersionInfoByType(Integer type) {
        return versionInfoMapper.getLastVersionInfoByType(type);
    }

    public VersionInfo getVersionInfoByVersionAndType(String version, Integer type) {
        VersionInfo versionInfo = new VersionInfo();
        versionInfo.setVersion(version);
        versionInfo.setType(type);
        return versionInfoMapper.selectOne(versionInfo);
    }

    public void delete(Long id) {
        VersionInfo versionInfo = versionInfoMapper.selectByPrimaryKey(id);
        FileUploadUtil.delFolder(staticPath + "/" + versionInfo.getType() + "/pkg/" + versionInfo.getVersion());
        FileUploadUtil.delFolder(staticPath + "/" + versionInfo.getType() + "/updatepkg/" + versionInfo.getVersion());
        versionInfoMapper.deleteByPrimaryKey(id);
    }

    public VersionInfo selectOne(VersionInfo versionInfo) {
        return versionInfoMapper.selectOne(versionInfo);
    }
}
